package com.cb.controller.front.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cb.common.webapp.context.RequestContext;
import com.cb.core.controller.BaseListController;
import com.cb.domain.model.system.SystemUser;
import com.cb.domain.model.user.UserAccount;

/**
 * 登录后的处理
 * @author sdm
 *
 */
@Controller
@RequestMapping("/postLoginAction.do")
public class PostLoginController extends BaseListController {
	
	@Override
	@RequestMapping
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		String url=getTargetUrl(request);		
		
		return new ModelAndView("redirect:"+url);
	}
	
	
	private String getTargetUrl(HttpServletRequest req) {

//		UserCompany userCompany=RequestContext.getCompanyUser();
		SystemUser sysUser=RequestContext.getCurrentSystemUser();
		UserAccount user=RequestContext.getCurrentUser();
		
		String targetUrl = null;
		
		HttpSession session=req.getSession(false);
		// retrieve saved requested url (saved by Acegi)
		if (session != null) {
			SavedRequest sq = (SavedRequest) session.getAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
			if (sq != null) {
				targetUrl = sq.getFullRequestUrl();
				session.removeAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
			}
		}
		// if no requested url, set to use default url
		if (targetUrl == null || "".equals(targetUrl)) {
//			if (userCompany != null&&userCompany.getUserType()==(short)1) {
//				targetUrl = "/storage/bbase/index.do";
//			} else if(userCompany != null&&userCompany.getUserType()==(short)2){
//				targetUrl = "/agent/agents/agentIndex.do";
//			}else if (sysUser != null) {
//				targetUrl = "/admin/system/index.do";
//			}else if (userCompany != null&&userCompany.getUserType()==(short)4) {
//				targetUrl = "/admin/system/index.do";
//			}
			if(user!=null){
				targetUrl = "/member/order/orders.do";
			}else if (sysUser != null) {
				targetUrl = "/admin/system/index.do";
				}
		}
		if(user!=null){
			session.setAttribute("currentUser",user);
		}else if (sysUser != null) {
			session.setAttribute("systemUser",sysUser);
			}
//		if (userCompany != null) 
//			session.setAttribute("currentUser",userCompany);
		return targetUrl;
	}
}
